package com.example.demo.web.service;

import com.example.demo.app.Exception;
import com.example.demo.app.cache.Cache;
import com.example.demo.app.sms.Sms;
import com.example.demo.web.entity.User;
import com.example.demo.web.entity.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class UserV1Service {

    @Autowired
    UserMapper userMapper;

    @Autowired
    Sms sms;

    // 验证码过期时间为60秒
    long expire = 60;

    Cache<String, String> cacheCaptcha = new Cache<>(expire);

    public boolean mobileExist(String mobile) {
        if (userMapper.mobileExist(mobile) > 0) {
            return true;
        }

        return false;
    }

    public User findByMobile(String mobile) {
        return userMapper.findByMobile(mobile);
    }

    public void sendCaptcha(String mobile) {

        // 生成四位随机数
        String captcha = String.valueOf((int)(Math.random() * 9000 + 1000));

        // 短信内容
        String content = String.format("%s为您的登录验证码，请于%s分钟内填写，如非本人操作，请忽略本短信。", captcha, expire / 60);

        // 调用sms接口发送短信
        sms.send(mobile, content);

        // 存入本地缓存
        cacheCaptcha.put(mobile, captcha);
    }

    public void validCaptcha(String mobile, String captcha) {
        String captchaCache =  cacheCaptcha.get(mobile);
        if (captchaCache == null) {
            throw new Exception("验证码已过期");
        }

        if (!captchaCache.equals(captcha)) {
            throw new Exception("验证码错误");
        }

        // 验证成功删除本地缓存
        cacheCaptcha.invalidate(mobile);
    }

    public User reLogin(String mobile) {

        User user = findByMobile(mobile);

        // 生成token
        String token = mobile + LocalDateTime.now().toString();
        token = DigestUtils.md5DigestAsHex(token.getBytes());
        user.setToken(token);

        // 设置登陆时间
        user.setLoginAt(LocalDateTime.now());

        userMapper.relogin(user.getId(), user.getToken(), user.getLoginAt());

        return user;
    }


    public User register(String mobile) {

        User user = new User();
        user.setMobile(mobile);

        // 生成昵称
        StringBuilder sb = new StringBuilder(mobile);
        String nickname =  sb.replace(3, 8, "*****").toString();
        user.setNickname(nickname);

        // 生成token
        String token = mobile + LocalDateTime.now().toString();
        token = DigestUtils.md5DigestAsHex(token.getBytes());
        user.setToken(token);

        // 设置登陆时间
        user.setLoginAt(LocalDateTime.now());

        Integer id = userMapper.register(user.getMobile(), user.getNickname(), user.getToken(), user.getLoginAt());
        user.setId(id);

        return user;
    }

    public void isMobile(String mobile) {
        Pattern p = Pattern.compile("^[1][3,4,5,6,7,8,9][0-9]{9}$");
        Matcher m = p.matcher(mobile);
        if  (!m.matches()) {
            throw new Exception("手机号格式不正确");
        }
    }

}
